var express = require('express');
var router = express.Router();
var md5 = require('md5');
var User = require('../models/user');
var Util = require('../common/util');
var upload = require('../common/fileuploads');


/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});


/***
 * POST  用户登录
 */
router.post('/login',function (req,res,next) {
      var params = req.body;
      if(!params){
          var dataError = {
              status: '0',
              msg: '参数不全'
          };
          res.end(JSON.stringify(dataError));
      }

      var username = params.username;
      var password = params.password;
      if (!username){
          var dataError = {
              status: '0',
              msg: '用户名参数不全'
          };
          res.end(JSON.stringify(dataError));
      }
      else if(!password){
          var dataError = {
              status: '0',
              msg: '密码参数不全'
          };
          res.end(JSON.stringify(dataError));
      }

      User.findOne({username:username},function (err,usr) {
            if(err){
                var dataError = {
                    status: '0',
                    msg: err.message
                };
                res.end(JSON.stringify(dataError));
            }
            else if(usr){
              if(usr.password!=md5(password)){
                  var dataError = {
                      status: '0',
                      msg: '用户名密码错误'
                  };
                  res.end(JSON.stringify(dataError));
              }
              else if(usr.loginstate == "1") {
                  var dataError = {
                      status: '0',
                      msg: '用户名已被禁用，请联系管理员'
                  };
                  res.end(JSON.stringify(dataError));
              }
              else {
                  var dataSuccess = {
                      status: '1',
                      msg: '登录成功',
                      data: {
                          _id:usr.id,
                          username: username,
                          password:usr.password,
                          role:usr.role,
                          departmentid:usr.departmentid,
                          nickname:usr.nickname,
                          gender: usr.gender,
                          age: usr.age,
                          birth: usr.birth,
                          address: usr.address,
                          email: usr.email,
                          telephone: usr.telephone,
                          duty: usr.duty,
                          handfreetelephone: usr.handfreetelephone,
                          qq: usr.qq,
                          weixin: usr.weixin,
                          dutystatus: usr.dutystatus,
                          headportrait: usr.headportrait,
                          loginstate: usr.loginstate,
                          createtime: usr.createtime,

                      }
                  };
                  res.end(JSON.stringify(dataSuccess));
              }

            }
            else {
                var dataError = {
                    status: '0',
                    msg: '用户不存在'
                };
                res.end(JSON.stringify(dataError));
            }
      });

});

/**
 * 创建用户
 */
router.post('/adduser',upload.single('avatar'),function (req,res,nex) {
    var params = req.body;
    if(!params){
        var dataError = {
            status: '0',
            msg: '参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    var username = params.username;
    var password = '123456';//新密码

    var departmentid = Util(params.departmentid);
    var nickname = Util(params.nickname);
    var gender = params.gender;
    var age = Util(params.age);
    var birth = Util(params.birth);
    var address = Util(params.address);
    var email = Util(params.email);
    var telephone = Util(params.telephone);
    var duty = Util(params.duty);
    var handfreetelephone = Util(params.handfreetelephone);

    var qq = Util(params.qq);
    var weixin = Util(params.weixin);
    var dutystatus = params.dutystatus;

    var headportrait = "";

    if(req.file){
        headportrait = "http://localhost:7000/"+Util(req.file.filename);
        // console.log(req.file);
        // console.log(req.body);
    }


    var role = params.role;//角色
    var loginstate = params.loginstate;//登录状态
    var operator = params.operator;//操作者



    if (!username){
        var dataError = {
            status: '0',
            msg: '用户名参数不全'
        };
        res.end(JSON.stringify(dataError));
    }
    else if(!role){
        var dataError = {
            status: '0',
            msg: '用户角色参数不全'
        };
        res.end(JSON.stringify(dataError));
    }
    else if(!Util(loginstate)&&loginstate!=0){
        var dataError = {
            status: '0',
            msg: '登录状态参数不全'
        };
        res.end(JSON.stringify(dataError));
    }
    // else if(!operator){
    //     var dataError = {
    //         status: '0',
    //         msg: '操作者参数不全'
    //     };
    //     res.end(JSON.stringify(dataError));
    // }

    User.findOne({username:username,isdelete:'0'},function (err,usr) {
        if(err){
            var dataError = {
                status: '0',
                msg: err.message
            };
            res.end(JSON.stringify(dataError));
        }
        else if(usr){
            var dataError = {
                status: '0',
                msg: '帐号已存在'
            };
            res.end(JSON.stringify(dataError));
        }
        else {
            var newUser = new User({
                username:username,
                password: md5(password),
                departmentid:departmentid,
                nickname:nickname,
                gender: gender,
                age: age,
                birth: birth,
                address: address,
                email: email,
                telephone: telephone,
                duty: duty,
                handfreetelephone: handfreetelephone,
                qq: qq,
                weixin: weixin,
                dutystatus: dutystatus,
                headportrait: headportrait,

                role:role,
                loginstate:loginstate,
                operator:operator
            });

            newUser.save(function (err) {
                if(err){
                    var dataError = {
                        status: '0',
                        msg: err.message
                    };
                    res.end(JSON.stringify(dataError));
                }
                else {
                    var dataSuccess = {
                        status: '1',
                        msg: '创建成功',
                    };
                    res.end(JSON.stringify(dataSuccess));
                }
            });
        }
    });
});



/**
 * 创建超级管理员 接口安全性，只能由后台开发人员或者负责人才能有权限调用这个接口，接口是隐藏的
 */
router.post('/addSAdmin',function (req,res,nex) {
    var params = req.body;
    if(!params){
        var dataError = {
            status: '0',
            msg: '参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    var username = params.username;
    var password = params.password;
    if (!username){
        var dataError = {
            status: '0',
            msg: '用户名参数不全'
        };
        res.end(JSON.stringify(dataError));
    }
    else if(!password){
        var dataError = {
            status: '0',
            msg: '密码参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    User.findOne({username:username},function (err,usr) {
        if(err){
            var dataError = {
                status: '0',
                msg: err.message
            };
            res.end(JSON.stringify(dataError));
        }
        else if(usr){
            var dataError = {
                status: '0',
                msg: '帐号已存在'
            };
            res.end(JSON.stringify(dataError));
        }
        else {
          var newUser = new User({
              username:username,
              password: md5(password),
              role:'0'
          });

            newUser.save(function (err) {
                if(err){
                    var dataError = {
                        status: '0',
                        msg: err.message
                    };
                    res.end(JSON.stringify(dataError));
                }
                else {
                    var dataSuccess = {
                        status: '1',
                        msg: '创建成功',
                        data: {
                            username: username
                        }
                    };
                    res.end(JSON.stringify(dataSuccess));
                }
            });
        }
    });
});

/**
 * 更新用户信息
 */
router.post('/updateuser',upload.single('avatar'),function (req,res,nex) {
    var params = req.body;
    if(!params){
        var dataError = {
            status: '0',
            msg: '参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    var id = params.id;
    var username = params.username;
    var role = params.role;//角色
    var loginstate = params.loginstate;//登录状态

    var departmentid = Util(params.departmentid);
    var nickname = Util(params.nickname);
    var gender = Util(params.gender);
    var age = Util(params.age);
    var birth = Util(params.birth);
    var address = Util(params.address);
    var email = Util(params.email);
    var telephone = Util(params.telephone);
    var duty = Util(params.duty);
    var handfreetelephone = Util(params.handfreetelephone);

    var qq = Util(params.qq);
    var weixin = Util(params.weixin);
    var dutystatus = Util(params.dutystatus);

    var headportrait = Util(params.headportrait);

    if(req.file){
        headportrait = "http://localhost:7000/"+Util(req.file.filename);
        // console.log(req.file);
        // console.log(req.body);
    }


    if (!id){
        var dataError = {
            status: '0',
            msg: '用户id参数不全'
        };
        res.end(JSON.stringify(dataError));
    }


    if (!username){
        var dataError = {
            status: '0',
            msg: '用户名参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

     if(!Util(loginstate)&&loginstate!=0){
        var dataError = {
            status: '0',
            msg: '登录状态参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    User.findOne({_id:id,isdelete:"0"},function (err,usr) {
        var whereStr = {"_id":id};

        if(err){
            var dataError = {
                status: '0',
                msg: err.message
            };
            res.end(JSON.stringify(dataError));
        }
        else if(usr){
            if(usr._id != id){
                var dataError = {
                    status: '0',
                    msg: '用户名已存在'
                };
                res.end(JSON.stringify(dataError));
            }
            else {
                var updateStr = {$set: {
                    "username" : username,
                    "loginstate" : loginstate,
                    "role" : role,
                    "departmentid" : departmentid ,
                    "nickname" : nickname ,
                    "gender" : gender ,
                    "age" : age ,
                    "birth" : birth ,
                    "address" : address ,
                    "email" : email ,
                    "telephone" : telephone ,
                    "duty" : duty ,
                    "handfreetelephone" : handfreetelephone ,
                    "qq" : qq ,
                    "weixin" : weixin ,
                    "dutystatus" : dutystatus ,
                    "headportrait" : headportrait

                }};
                User.update(whereStr,updateStr,function () {
                    if(err){
                        var dataError = {
                            status: '0',
                            msg: err.message
                        };
                        res.end(JSON.stringify(dataError));
                    }
                    else {
                        var dataSuccess = {
                            status: '1',
                            msg: '更新成功'
                        };
                        res.end(JSON.stringify(dataSuccess));
                    }

                });
            }
        }
        else {
            var updateStr = {$set: {
                "username" : username,
                "loginstate" : loginstate,
                "role" : role,
                "departmentid" : departmentid ,
                "nickname" : nickname ,
                "gender" : gender ,
                "age" : age ,
                "birth" : birth ,
                "address" : address ,

                "email" : email ,
                "telephone" : telephone ,
                "duty" : duty ,
                "handfreetelephone" : handfreetelephone ,
                "qq" : qq ,
                "weixin" : weixin ,
                "dutystatus" : dutystatus ,
                "headportrait" : headportrait

            }};
            User.update(whereStr,updateStr,function () {
                if(err){
                    var dataError = {
                        status: '0',
                        msg: err.message
                    };
                    res.end(JSON.stringify(dataError));
                }
                else {
                    var dataSuccess = {
                        status: '1',
                        msg: '更新成功'
                    };
                    res.end(JSON.stringify(dataSuccess));
                }

            });
        }
    });
});

/**
 * 删除用户信息（更新字段，没有真正删除数据）
 */
router.post('/deleteuser',function (req,res,nex) {
    var params = req.body;
    if(!params){
        var dataError = {
            status: '0',
            msg: '参数不全'
        };
        res.end(JSON.stringify(dataError));
    }

    var ids = params.ids;

    if (!ids){
        var dataError = {
            status: '0',
            msg: '没有选择删除用户'
        };
        res.end(JSON.stringify(dataError));
    }

    var array = ids.split(',');
    for(var i = 0 ;i <array.length ; i++ )
    {
        User.update({"_id":array[i]},{"$set":{"isdelete":"1"}},function (err) {
            callMeBack(i);
        })
    }


    function callMeBack(index) {
        if(index == array.length){
            var dataSuccess = {
                status: '1',
                msg: '数据删除成功'
            };
            res.end(JSON.stringify(dataSuccess));
        }
    }

});



/**
 * 获取用户列表
 */
router.post('/userlist',function (req,res,nex) {
    var count = 0;
    var page = req.body.page;
    var rows = req.body.rows;
    var isdelete = req.body.isdelete;

    var username = req.body.username;
    var query = User.find({});

    if(!page){
        page = 1;
    }

    if(!rows){
        rows = 10;
    }

    query.skip((page-1)*rows);


    query.limit(rows*1);


    if(username){
        var qs=new RegExp(username);
        query.where('username',qs);
    }

    if(isdelete){
        query.where('isdelete',isdelete);
    }
    else {
        query.where('isdelete','0');
    }

    //计算分页数据
    query.exec(function(err,rs){
        if(err){
            var dataError = {
                status: '0',
                msg: err.message
            };
            res.end(JSON.stringify(dataError));


        }else{

            var qs=new RegExp(username);
            User.find({username:qs,isdelete:'0'}).sort({'_id':-1}).exec(function (err,list) {

                if(err){
                    var dataError = {
                        status: '0',
                        msg: err.message
                    };
                    res.end(JSON.stringify(dataError));
                }
                else {
                    var dataSuccess = {
                        status: '1',
                        data:rs,
                        sumpage:list.length,
                        msg: '查询成功'
                    };
                    res.end(JSON.stringify(dataSuccess));
                }

            });

        }
    });
});





module.exports = router;
